package bgate.hung.activity;

import java.util.Vector;
import bgate.connector.DataTransfer;
import bgate.hung.workerclass.PhomView;
import android.view.View.OnClickListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import bgate.hung.workerclass.PhomView.GameThread;

public class PhomActivity extends Activity {
	private final static String TAG = "GamePlayActivity";
	private final static int TIME_DELAY = 1000;
	private final static int DIALOG_CHAT = 1;
	private final static int DIALOG_SO_NGUOI_CHOI = 2;
	private final static int DIALOG_KET_BAN = 3;
	private final static int DIALOG_TIEN_CUOC = 4;
	private final static int DIALOG_KICK = 5;
	private DataTransfer dataTransfer;
	private IncommingMessage incommingMessage = null;
	private GameThread gameThread;
	private PhomView phomView;
	private String[] ro_arr;
	private int[] mo_arr;
	private int[] re_arr;
	private boolean isPushTask = false;
	private Vector<Integer> mo_vector = new Vector<Integer>();
	private Vector<Integer> sc_vector = new Vector<Integer>();
	private Vector<Integer> db_vector = new Vector<Integer>();
	private Vector<Integer> ea_vector = new Vector<Integer>();
	private Vector<Integer> id_cm_vector = new Vector<Integer>();
	private Vector<Integer> money_cm_vector = new Vector<Integer>();
	private Vector<Integer> hp_vector = new Vector<Integer>();
	private Vector<Integer> fn_vector0 = new Vector<Integer>();
	private Vector<Integer> fn_vector1 = new Vector<Integer>();
	private Vector<Integer> fn_vector2 = new Vector<Integer>();
	private Vector<Integer> fn_vector3 = new Vector<Integer>();
	private int bc_data;
	private int fs_data;
	private int u_data;
	private int den_lang;
	private int bi_den_lang;
	private boolean readROMessage = false;
	private boolean readMOMessage = false;
	private boolean readREMessage = false;
	private boolean readFN0 = false;
	private boolean readFN1 = false;
	private boolean readFN2 = false;
	private boolean readFN3 = false;
	private long lastWaitting = 0l;
	private Toast toast;
	private boolean isToast = false;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		String acc = "";
		Intent intent = getIntent();
		acc = intent.getStringExtra("ACCOUNT");
		ro_arr = intent.getStringArrayExtra("RO_ARRAY");
		mo_arr = intent.getIntArrayExtra("MO_ARRAY");
		re_arr = intent.getIntArrayExtra("RE_ARRAY");

		dataTransfer = DataTransfer.getInstance();
		if (incommingMessage == null)
			incommingMessage = new IncommingMessage(dataTransfer.getOutQueue());
		if (!isPushTask && incommingMessage != null) {
			dataTransfer.putTask(incommingMessage);
			isPushTask = true;
		}

		phomView = new PhomView(this);
		gameThread = phomView.getThread();
		gameThread.setUserInfor(acc);
		gameThread.setTableData(ro_arr, mo_arr, re_arr, true, true, true);
		setContentView(phomView);
	}

	public void onBackPressed() {
		dataTransfer = DataTransfer.getInstance();
		dataTransfer.requestData("}RRO|&");
		Intent result = new Intent();
		result.putExtra("KICK", false);
		setResult(RESULT_OK, result);
		finish();
	}

	public void onResume() {
		super.onResume();
	}

	protected Dialog onCreateDialog(int id) {
		// switch (id) {
		// case DIALOG_CHAT:
		// LayoutInflater factory1 = LayoutInflater.from(this);
		// final View chatView = factory1.inflate(R.layout.dialog_chat_view,
		// null);
		// final EditText chatEditText = (EditText) chatView
		// .findViewById(R.id.chat_editText);
		// final Button sendButton = (Button) chatView
		// .findViewById(R.id.send_button);
		// AlertDialog.Builder builder = new
		// AlertDialog.Builder(PhomActivity.this);
		// final AlertDialog alert = builder.setView(chatView).create();
		// sendButton.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// String message = chatEditText.getText().toString();
		// sendChatData(message);
		// gameThread.setMeChat(message);
		// alert.cancel();
		// }
		// });
		// return alert;
		// case DIALOG_TIEN_CUOC:
		// LayoutInflater factory2 = LayoutInflater.from(this);
		// final View moneyView = factory2.inflate(
		// R.layout.dialog_edit_text_view, null);
		// final EditText moneyEditText = (EditText) moneyView
		// .findViewById(R.id.dialog_editText);
		// return new AlertDialog.Builder(PhomActivity.this)
		// .setView(moneyView)
		// .setTitle("Thiết lập ti�?n cược")
		// .setPositiveButton("�?ồng ý",
		// new DialogInterface.OnClickListener() {
		//
		// @Override
		// public void onClick(DialogInterface dialog,
		// int which) {
		// // TODO Auto-generated method stub
		// sendMSData(moneyEditText.getText()
		// .toString());
		// }
		// })
		// .setNegativeButton("Hủy",
		// new DialogInterface.OnClickListener() {
		//
		// @Override
		// public void onClick(DialogInterface dialog,
		// int which) {
		// // TODO Auto-generated method stub
		//
		// }
		// }).create();
		// case DIALOG_SO_NGUOI_CHOI:
		// String[] arr = { "2 ngư�?i chơi", "3 ngư�?i chơi", "4 ngư�?i chơi" };
		// return new AlertDialog.Builder(PhomActivity.this)
		// .setTitle("Thiết lập số ngư�?i chơi")
		// .setItems(arr, new DialogInterface.OnClickListener() {
		//
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// // TODO Auto-generated method stub
		// if (which == 0) {
		// sendSUData("2");
		// } else if (which == 1) {
		// sendSUData("3");
		// } else if (which == 2) {
		// sendSUData("4");
		// }
		// }
		// }).create();
		// case DIALOG_KICK:
		// final String[] user = gameThread.getPlayerActivited();
		// return new AlertDialog.Builder(PhomActivity.this)
		// .setTitle("Kick ngư�?i chơi")
		// .setItems(user, new DialogInterface.OnClickListener() {
		//
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// // TODO Auto-generated method stub
		// sendKICKData(user[which]);
		// }
		// }).create();
		// }
		return null;
	}

	public void setToast(String text) {
		if (!isToast) {
			isToast = true;
			gameThread.setToast();
			toast = Toast.makeText(PhomActivity.this, text, Toast.LENGTH_SHORT);
			toast.show();
		}
	}

	public void stopToast() {
		toast.cancel();
		isToast = false;
	}

	public void onPause() {
		super.onPause();
		if (isPushTask) {
			dataTransfer.removeTask(incommingMessage);
			isPushTask = false;
		}
		incommingMessage = null;
	}

	public void sendEARequest(int id_acc, int id_db, int chot) {
		dataTransfer.requestData("}EA|" + id_acc + "|" + id_db + "|" + chot
				+ "&");
	}

	public void sendReadyData() {
		dataTransfer.requestData("}RE|1&");
	}

	public void sendNotReadyData() {
		dataTransfer.requestData("}RE|0&");
	}

	public void sendUData(String s) {
		dataTransfer.requestData("}U|" + s + "&");
	}

	public void sendDBData(int id_me, int id_db) {
		dataTransfer.requestData("}DB|" + id_me + "|" + id_db + "&");
	}

	public void sendHPData(int stt, Vector<Integer> v) {
		String s = "";
		s += Integer.toString(stt) + "|";
		for (int i = 0; i < v.size(); i++) {
			s += Integer.toString(v.elementAt(i)) + "|";
		}
		dataTransfer.requestData("}HP|" + s + "&");
	}

	public void sendTCData() {
		dataTransfer.requestData("CT|0&");
	}

	public void sendSCOData(Vector<Integer> v) {
		String s = "";
		for (int i = 0; i < v.size(); i++) {
			s += Integer.toString(v.elementAt(i)) + "|";
		}
		dataTransfer.requestData("}SCO|" + s + "&");
	}

	public void sendFNData() {
		dataTransfer.requestData("}FN|&");
	}

	public void sendMSData(String s) {
		dataTransfer.requestData("}MS|" + s + "&");
	}

	public void sendSUData(String s) {
		dataTransfer.requestData("}SU|" + s + "&");
	}

	public void sendKICKData(String s) {
		dataTransfer.requestData("}KICK|" + s + "&");
	}

	public void sendChatData(String s) {
		dataTransfer.requestData("}CHAT|" + s + "&");
	}

	public void setBCData() {
		gameThread.setBCData(bc_data);
	}

	public void setEAData() {
		gameThread.setEAData(ea_vector);
	}

	public void sendNBRequest() {
		dataTransfer.requestData("}NB|&");
	}

	public void showDialogChat() {
		showDialogChat.sendEmptyMessage(0);
	}

	public void showDialogMoneySetting() {
		showMoneySetting.sendEmptyMessage(0);
	}

	public void showDialogUserSetting() {
		showUserSetting.sendEmptyMessage(0);
	}

	public void showDialogKick() {
		showDialogKick.sendEmptyMessage(0);
	}

	final Handler showDialogChat = new Handler() {
		public void handleMessage(Message msg) {
			showDialog(DIALOG_CHAT);
		}
	};

	final Handler showMoneySetting = new Handler() {
		public void handleMessage(Message msg) {
			showDialog(DIALOG_TIEN_CUOC);
		}
	};

	final Handler showUserSetting = new Handler() {
		public void handleMessage(Message msg) {
			showDialog(DIALOG_SO_NGUOI_CHOI);
		};
	};

	final Handler showDialogKick = new Handler() {
		public void handleMessage(Message msg) {
			showDialog(DIALOG_KICK);
		}
	};

	private void setSCData() {
		gameThread.setSCVector(sc_vector, mo_vector);
	}

	private void setDBData() {
		gameThread.setDBData(db_vector);
	}

	private void setCMData() {
		gameThread.setCMData(id_cm_vector, money_cm_vector);
		id_cm_vector.removeAllElements();
		money_cm_vector.removeAllElements();
	}

	private void setHPData() {
		gameThread.setHPData(hp_vector);
	}

	private void setFSData() {
		gameThread.setPlayerStart(fs_data);
		gameThread.startClock(true);
	}

	private void setFNData() {
		gameThread.setFNData(fn_vector0, fn_vector1, fn_vector2, fn_vector3);
	}

	private void setUData() {
		gameThread.setUData(u_data);
	}

	private void setDLData() {
		gameThread.setDLData(den_lang, bi_den_lang);
	}

	private void setChatData(int i, String s) {
		gameThread.setChatData(i, s);
	}

	private void setKick() {
		Intent result = new Intent();
		result.putExtra("KICK", true);
		setResult(RESULT_OK, result);
		finish();
	}

	private void setOut() {
		Intent result = new Intent();
		result.putExtra("KICK", false);
		setResult(RESULT_OK, result);
		finish();
	}

	final Handler showAlertHandler = new Handler() {
		public void handleMessage(Message msg) {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					PhomActivity.this);
			builder.setMessage("Kết nối mạng bị lỗi!")
					.setCancelable(false)
					.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									setNavigation();
								}
							});
			AlertDialog alert = builder.create();
			alert.show();
		}
	};

	private void setNavigation() {
		Intent intent = new Intent(this, Login.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
	}

	private class IncommingMessage implements Runnable {
		private Vector _inQueue;

		public IncommingMessage(Vector outQueue) {
			System.out.println("Push Task");
			_inQueue = outQueue;
		}

		public void run() {
			// TODO Auto-generated method stub
			try {
				Thread.sleep(10);
				if (_inQueue.size() > 0) {
					String data = (String) _inQueue.elementAt(0);
					_inQueue.removeElementAt(0);
					Log.d(TAG, data);
					Vector<String> tempResultData = splitString(data, '}');
					for (int k = 0; k < tempResultData.size(); k++) {
						Vector<String> resultData = splitString(
								tempResultData.elementAt(k), '|');
						for (int i = 0; i < resultData.size(); i++) {
							String s = resultData.elementAt(i);
							if (s.equals("RO")) {
								ro_arr = new String[resultData.size() - i - 1];
								int index = 0;
								for (int j = i + 1; j < resultData.size(); j++) {
									s = resultData.elementAt(j);
									ro_arr[index] = s;
									index++;
								}
								gameThread.setTableData(ro_arr, mo_arr, re_arr,
										true, false, false);
								break;
							}

							if (s.equals("MO")) {
								mo_arr = new int[resultData.size() - i - 1];
								int index = 0;
								for (int j = i + 1; j < resultData.size(); j++) {
									s = resultData.elementAt(j);
									mo_arr[index] = Integer.valueOf(s);
									index++;
								}
								gameThread.setTableData(ro_arr, mo_arr, re_arr,
										false, true, false);
								break;
							}

							if (s.equals("RE")) {
								re_arr = new int[resultData.size() - i - 1];
								int index = 0;
								for (int j = i + 1; j < resultData.size(); j++) {
									s = resultData.elementAt(j);
									re_arr[index] = Integer.valueOf(s);
									index++;
								}
								gameThread.setTableData(ro_arr, mo_arr, re_arr,
										false, false, true);
								break;
							}

							if (s.equals("SC")) {
								sc_vector.removeAllElements();
								for (int j = i + 1; j < resultData.size(); j++) {
									s = resultData.elementAt(j);
									if (s.equals("MO"))
										break;
									else
										sc_vector
												.addElement(Integer.valueOf(s));
								}
								mo_vector.removeAllElements();
								for (int j = i + 1; j < resultData.size(); j++) {
									s = resultData.elementAt(j);
									if (s.equals("MO")) {
										for (int l = j + 1; l < resultData
												.size(); l++) {
											s = resultData.elementAt(l);
											mo_vector.addElement(Integer
													.valueOf(s));
										}
										break;
									}
								}
								setSCData();
								break;
							}

							if (s.equals("DB")) {
								db_vector.removeAllElements();
								for (int j = i + 1; j < resultData.size(); j++) {
									s = resultData.elementAt(j);
									db_vector.addElement(Integer.valueOf(s));
								}
								setDBData();
								break;
							}

							if (s.equals("BC")) {
								s = resultData.elementAt(i + 1);
								bc_data = Integer.valueOf(s);
								setBCData();
								break;
							}

							if (s.equals("EA")) {
								ea_vector.removeAllElements();
								for (int j = i + 1; j < resultData.size(); j++) {
									s = resultData.elementAt(j);
									ea_vector.addElement(Integer.valueOf(s));
								}
								setEAData();
								break;
							}

							if (s.equals("CM")) {
								id_cm_vector.addElement(Integer
										.valueOf(resultData.elementAt(i + 1)));
								money_cm_vector.addElement(Integer
										.valueOf(resultData.elementAt(i + 2)));
								break;
							}

							if (s.equals("FCM")) {
								setCMData();
								break;
							}

							if (s.equals("HP")) {
								hp_vector.removeAllElements();
								for (int j = i + 1; j < resultData.size(); j++) {
									s = resultData.elementAt(j);
									hp_vector.addElement(Integer.valueOf(s));
								}
								setHPData();
								break;
							}

							if (s.equals("FS")) {
								s = resultData.elementAt(i + 1);
								fs_data = Integer.valueOf(s);
								setFSData();
								break;
							}

							if (s.equals("FN")) {
								fn_vector0.removeAllElements();
								fn_vector1.removeAllElements();
								fn_vector2.removeAllElements();
								fn_vector3.removeAllElements();
								for (int j = i; j < resultData.size(); j++) {
									s = resultData.elementAt(j);
									if (s.equals("FN")) {
										j++;
										s = resultData.elementAt(j);
										if (s.equals("0")) {
											readFN0 = true;
											readFN1 = false;
											readFN2 = false;
											readFN3 = false;
											continue;
										} else if (s.equals("1")) {
											readFN0 = false;
											readFN1 = true;
											readFN2 = false;
											readFN3 = false;
											continue;
										} else if (s.equals("2")) {
											readFN0 = false;
											readFN1 = false;
											readFN2 = true;
											readFN3 = false;
											continue;
										} else if (s.equals("3")) {
											readFN0 = false;
											readFN1 = false;
											readFN2 = false;
											readFN3 = true;
											continue;
										}
									}
									if (readFN0) {
										fn_vector0.addElement(Integer
												.valueOf(s));
									} else if (readFN1) {
										fn_vector1.addElement(Integer
												.valueOf(s));
									} else if (readFN2) {
										fn_vector2.addElement(Integer
												.valueOf(s));
									} else if (readFN3) {
										fn_vector3.addElement(Integer
												.valueOf(s));
									}
								}
								setFNData();
								break;
							}

							if (s.equals("U")) {
								s = resultData.elementAt(i + 1);
								u_data = Integer.valueOf(s);
								setUData();
								break;
							}

							if (s.equals("DL")) {
								s = resultData.elementAt(i + 1);
								den_lang = Integer.valueOf(s);
								s = resultData.elementAt(i + 2);
								bi_den_lang = Integer.valueOf(s);
								setDLData();
							}

							if (s.equals("CHAT")) {
								s = resultData.elementAt(i + 1);
								String message = s;
								s = resultData.elementAt(i + 2);
								int stt = Integer.valueOf(s);
								setChatData(stt, message);
								break;
							}

							if (s.equals("OFFLINE")) {
								Log.d(TAG, "MAT MANG");
								showAlertHandler.sendEmptyMessage(0);
							}

							if (s.equals("KICK")) {
								Log.d(TAG, "BI KICK KHOI BAN");
								setKick();
							}

							if (s.equals("US")) {
								Log.d(TAG, "BI OUT KHOI BAN");
								setOut();
							}
						}
					}
				}
			} catch (InterruptedException ex) {
				Log.d(TAG, ex.toString());
			} catch (NullPointerException ex) {
				Log.d(TAG, ex.toString());
			}
		}

	}

	private Vector<String> splitString(String string, char delimiter) {
		Vector<String> result = new Vector<String>();
		TextUtils.StringSplitter splitter = new TextUtils.SimpleStringSplitter(
				delimiter);

		// Once per string to split
		splitter.setString(string);
		for (String s : splitter) {
			String temp = "";
			for (int i = 0; i < s.length(); i++) {
				if (s.charAt(i) != '}' && s.charAt(i) != '&')
					temp += s.charAt(i);
			}
			result.addElement(temp);
		}

		return result;
	}

}
